from django import forms
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST

from StuApp.models import UserInfo


class RegisterForm(forms.ModelForm):
    username = forms.CharField(min_length=3, widget=forms.TextInput(attrs={'placeholder': "账号"}))
    password = forms.CharField(min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "密码"}))
    password2 = forms.CharField(min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "确认密码"}))

    class Meta:
        model = UserInfo
        fields = ['username', 'password', 'password2']


class AdminForm(forms.ModelForm):
    username = forms.CharField(
        label="账号",
        min_length=3,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': True,
            'placeholder': '账号'
        })
    )
    password1 = forms.CharField(
        label="密码",
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'required': True,
            'placeholder': '密码'
        })
    )

    password2 = forms.CharField(
        label="确认密码",
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'required': True,
            'placeholder': '确认密码'
        })
    )

    class Meta:
        model = UserInfo
        fields = ['username', 'password1', 'password2']


# 系统用户管理界面
def userHub(request):
    user_id = request.session.get('user_id')
    user = UserInfo.objects.filter(username=user_id).first()
    if not user or not user.is_superuser:
        return render(request, "no_permission.html")  
    
    if request.method == 'POST':
        action = request.POST.get('action')

        if action == 'search':
            search_term = request.POST.get('search_term', '')
            admins = UserInfo.objects.filter(username__icontains=search_term)
            admin_list = [{'username': admin.username, 'password': admin.password} for admin in admins]
            return JsonResponse({'status': 'success', 'admins': admin_list})

        elif action == 'reset_password':
            try:
                admin_id = request.POST.get('id')
                admin = UserInfo.objects.get(username=admin_id)
                admin.password = admin.username + '@123Jxust'
                admin.save()
                return JsonResponse({'status': 'success'})
            except UserInfo.DoesNotExist:
                return JsonResponse({'status': 'error', 'message': '管理员不存在！'})
            except Exception as e:
                return JsonResponse({'status': 'error', 'message': str(e)})

        elif action == 'delete':
            try:
                admin_id = request.POST.get('id')
                admin = UserInfo.objects.get(username=admin_id)
                admin.delete()
                return JsonResponse({'status': 'success'})
            except UserInfo.DoesNotExist:
                return JsonResponse({'status': 'error', 'message': '管理员不存在！'})
            except Exception as e:
                return JsonResponse({'status': 'error', 'message': str(e)})

    # GET请求处理
    admin = UserInfo.objects.all().order_by('username')
    search_key = request.GET.get('q', '')
    if search_key:
        admin = admin.filter(username__icontains=search_key)

    paginator = Paginator(admin, 10)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)

    context = {
        "admins": page_obj,
        "page_obj": page_obj,
        "search_key": search_key,
    }
    return render(request, "user_hub.html", context)


# 添加管理员
def addAdmin(request):
    if request.method == 'POST':
        form = AdminForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            password1 = form.cleaned_data['password1']
            password2 = form.cleaned_data['password2']

            # 检查密码是否一致
            if password1 != password2:
                form.add_error('password2', '两次密码不一致')
                return render(request, "add.html", {"form": form, "title": "管理员"})

            # 检查账号是否已存在
            if UserInfo.objects.filter(username=username).exists():
                form.add_error('username', '账号已存在')
                return render(request, "add.html", {"form": form, "title": "管理员"})

            # 如果所有检查都通过，保存用户
            user = form.save(commit=False)
            user.password = password1  # 使用第一个密码作为最终密码
            user.save()
            messages.success(request, '管理员添加成功！')
            return redirect('user_hub')
    else:
        form = AdminForm()
    return render(request, "add.html", {"form": form, "title": "管理员"})


# 重置密码为username+@123Jxust
def resetPassword(request, admin_id):
    if request.method == 'POST':
        try:
            admin = UserInfo.objects.get(username=admin_id)
            admin.password = admin.username + '@123Jxust'
            admin.save()
            messages.success(request, '密码重置成功！')
        except UserInfo.DoesNotExist:
            messages.error(request, '管理员不存在！')
        except Exception as e:
            messages.error(request, f'操作失败：{str(e)}')
    return redirect('user_hub')


# 删除管理员
def deleteAdmin(request, admin_id):
    if request.method == 'POST':
        try:
            admin = UserInfo.objects.get(username=admin_id)
            admin.delete()
            messages.success(request, '管理员删除成功！')
        except UserInfo.DoesNotExist:
            messages.error(request, '管理员不存在！')
        except Exception as e:
            messages.error(request, f'删除失败：{str(e)}')
    return redirect('user_hub')


# 修改超级管理员权限
@require_POST
def toggle_superuser(request, admin_id):
    user_id = request.session.get('user_id')
    user = UserInfo.objects.filter(username=user_id).first()
    if not user or not user.is_superuser:
        return JsonResponse({'status': 'error', 'message': '无权限操作'})

    if user_id == admin_id:
        return JsonResponse({'status': 'error', 'message': '不能修改自己的超级管理员权限'})

    try:
        admin = UserInfo.objects.get(username=admin_id)
        admin.is_superuser = not admin.is_superuser
        admin.save()
        return JsonResponse({'status': 'success', 'is_superuser': admin.is_superuser})
    except UserInfo.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '管理员不存在'})
